package com.cb2.algorithm.leetcode;

/**
 * <a href='https://leetcode.cn/problems/reverse-string-ii'>反转字符串 II(Reverse String II)</a>
 * <p>给定一个字符串 s 和一个整数 k，从字符串开头算起，每计数至 2k 个字符，就反转这 2k 字符中的前 k 个字符。
 *  <ul>
 *     <li>如果剩余字符少于 k 个，则将剩余字符全部反转。</li>
 *     <li>如果剩余字符小于 2k 但大于或等于 k 个，则反转前 k 个字符，其余字符保持原样。</li>
 *  </ul>
 * </p>
 *
 * <p>
 * <b>示例：</b>
 * <pre>
 *  示例 1：
 *      输入：s = "abcdefg", k = 2
 *      输出："bacdfeg"
 *
 *  示例 2：
 *      输入：s = "abcd", k = 2
 *      输出："bacd"
 * </pre>
 * </p>
 *
 * <p>
 *
 * <b>提示：</b>
 * <ul>
 *     <li>1 <= s.length <= 10^4</li>
 *     <li>s 仅由小写英文组成</li>
 *     <li>1 <= k <= 10^4</li>
 * </ul>
 * </p>
 *
 * @author c2b
 * @see LC0344ReverseString_S 反转字符串
 * @see LC0541ReverseString_II_S 反转字符串 II
 * @since 2025/2/7 15:05
 */
public class LC0541ReverseString_II_S {
    static class Solution {
        public String reverseStr(String s, int k) {
            if (k == 1) {
                return s;
            }
            int m = s.length() / k;
            char[] chars = s.toCharArray();
            for (int i = 0; i < chars.length; i += 2 * k) {
                int left = i;
                // 最大反转k个
                int right = Math.min(chars.length - 1, left + k - 1);
                while (left < right) {
                    char temp = chars[left];
                    chars[left] = chars[right];
                    chars[right] = temp;
                    ++left;
                    --right;
                }
            }
            return new String(chars);
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.reverseStr("abcdefg", 2));
        System.out.println(solution.reverseStr("abcd", 2));
    }
}
